package shared;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.security.MessageDigest;

import client.Configuration;

public class Utilities
{
    public static String computeHash(String pathName)
    {
	byte[] hashedStream = null;
	byte[] buf = new byte[1024];
	FileInputStream originalFile = null;
	BufferedInputStream file = null;

	int bytesRead;
	try
	{
	    originalFile = new FileInputStream(pathName);
	    file = new BufferedInputStream(originalFile);

	    MessageDigest hasher = MessageDigest.getInstance(Constants.HASH_METHOD);

	    while (true)
	    {
		bytesRead = file.read(buf);
		if (bytesRead < 0)
		{
		    break;
		}
		hasher.update(buf, 0, bytesRead);
	    }

	    file.close();
	    hashedStream = hasher.digest();

	} catch (Exception e)
	{
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

	String hash = "";
	if (hashedStream == null) return hash;
	for (int i = 0; i < hashedStream.length; i++)
	{
	    hash += Integer.toString((hashedStream[i] & 0xff) + 0x100, 16)
		    .substring(1);
	}
	return hash;
    }
    
    public static String computeHashFromBytes(byte[] bytes)
    {
	byte[] hashedStream = null;

	int bytesRead;
	try
	{
	    MessageDigest hasher = MessageDigest.getInstance(Constants.HASH_METHOD);
		hasher.update(bytes);
	    hashedStream = hasher.digest();

	} catch (Exception e)
	{
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

	String hash = "";

	for (int i = 0; i < hashedStream.length; i++)
	{
	    hash += Integer.toString((hashedStream[i] & 0xff) + 0x100, 16)
		    .substring(1);
	}
	return hash;
    }
}
